﻿module Sustainalytics.EsgRatings {

    import Company = Sustainalytics.Company;

    export class HistoricalPerformanceController {

        public esgHistoricalPerformanceSummary: EsgHistoricalPerformanceSummaryDto;
        public esgOverallPerformanceSummarySerialChartOptions: Charts.SerialChartOptions;
        public esgEnvironmentPerformanceSummarySerialChartOptions: Charts.SerialChartOptions;
        public esgSocialPerformanceSummarySerialChartOptions: Charts.SerialChartOptions;
        public esgGovernancePerformanceSummarySerialChartOptions: Charts.SerialChartOptions;

        public overallChartIsLoading: boolean = true;
        public environmentChartIsLoading: boolean = true;
        public socialChartIsLoading: boolean = true;
        public governanceChartIsLoading: boolean = true;


        constructor(
            private $scope: Company.ICompanyBasedScope,
            private $q: ng.IQService,
            private $timeout: ng.ITimeoutService,
            private $filter: ng.IFilterService,
            private EsgHistoricalPerformanceSummaryService: IEsgHistoricalPerformanceSummaryService,
            private NumberUtilityService: Common.NumberUtilityService,
            private $rootScope) {

            var ctx = this;
            ctx.init();
        }

        private init(): ng.IPromise<any> {
            var ctx = this;

            var promiseHistorical = ctx.getEsgHistoricalPerformanceSummary();

            return promiseHistorical;
        }

        private getEsgHistoricalPerformanceSummary(): ng.IPromise<EsgHistoricalPerformanceSummaryDto> {
            var ctx = this;
            var promise = ctx.EsgHistoricalPerformanceSummaryService.get(ctx.$scope.currentCompany.id);

            promise.then(function (res) {
                ctx.$timeout(function () {
                    ctx.$scope.$apply(function () {
                        ctx.esgHistoricalPerformanceSummary = res;

                        // create Serial Chart data sources
                        ctx.esgOverallPerformanceSummarySerialChartOptions = ctx.createEsgOverallPerformanceSummarySerialChartOptions();
                        ctx.esgEnvironmentPerformanceSummarySerialChartOptions = ctx.createEsgEnvironmentPerformanceSummarySerialChartOptions();
                        ctx.esgSocialPerformanceSummarySerialChartOptions = ctx.createEsgSocialPerformanceSummarySerialChartOptions();
                        ctx.esgGovernancePerformanceSummarySerialChartOptions = ctx.createEsgGovernancePerformanceSummarySerialChartOptions();
                    });
                });
            },() => {

                    ga('create', 'UA-4379897-6', {
                        'userId': ctx.$rootScope.userInfo.userId, 'cookieDomain': 'none', 'name': 'globalAccess'
                    });

                    ga('globalAccess.send', 'exception', { 'exDescription': 'Esg Ratings: HistoricalPerformance Controller -> Error loading Historical Performance Summary' });
                });

            return promise;
        }

        private createEsgOverallPerformanceSummarySerialChartOptions(): Charts.SerialChartOptions {
            var ctx = this;

            var scoreDic = new Common.Dictionary<SerialChartEsgMonthlyScore>();

            // for each current company add its score
            $.each(ctx.esgHistoricalPerformanceSummary.overall.companyHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.currentScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry leader add its score
            $.each(ctx.esgHistoricalPerformanceSummary.overall.industryLeaderHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.leaderScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry avg add its score
            $.each(ctx.esgHistoricalPerformanceSummary.overall.peerGroupAvgHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.avgScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });


            // get chart scores
            var chartScores = scoreDic.getValues();

            var chartOptions = ctx.createOverallSerialChartOptions();
            chartOptions.dataProvider = chartScores;

            return chartOptions;
        }

        private createEsgEnvironmentPerformanceSummarySerialChartOptions(): Charts.SerialChartOptions {
            var ctx = this;

            var scoreDic = new Common.Dictionary<SerialChartEsgMonthlyScore>();

            // for each current company add its score
            $.each(ctx.esgHistoricalPerformanceSummary.environment.companyHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.currentScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry leader add its score
            $.each(ctx.esgHistoricalPerformanceSummary.environment.industryLeaderHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.leaderScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry avg add its score
            $.each(ctx.esgHistoricalPerformanceSummary.environment.peerGroupAvgHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.avgScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });


            // get chart scores
            var chartScores = scoreDic.getValues();

            var chartOptions = ctx.createThemeSerialChartOptions('Environment');
            chartOptions.dataProvider = chartScores;

            return chartOptions;
        }

        private createEsgSocialPerformanceSummarySerialChartOptions(): Charts.SerialChartOptions {
            var ctx = this;

            var scoreDic = new Common.Dictionary<SerialChartEsgMonthlyScore>();

            // for each current company add its score
            $.each(ctx.esgHistoricalPerformanceSummary.social.companyHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.currentScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry leader add its score
            $.each(ctx.esgHistoricalPerformanceSummary.social.industryLeaderHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.leaderScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry avg add its score
            $.each(ctx.esgHistoricalPerformanceSummary.social.peerGroupAvgHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.avgScore = score.score == null ? "null": ctx.$filter('number')(score.score, 2);
            });


            // get chart scores
            var chartScores = scoreDic.getValues();

            var chartOptions = ctx.createThemeSerialChartOptions('Social');
            chartOptions.dataProvider = chartScores;

            return chartOptions;
        }

        private createEsgGovernancePerformanceSummarySerialChartOptions(): Charts.SerialChartOptions {
            var ctx = this;

            var scoreDic = new Common.Dictionary<SerialChartEsgMonthlyScore>();

            // for each current company add its score
            $.each(ctx.esgHistoricalPerformanceSummary.governance.companyHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.currentScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry leader add its score
            $.each(ctx.esgHistoricalPerformanceSummary.governance.industryLeaderHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.leaderScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });

            // for each industry avg add its score
            $.each(ctx.esgHistoricalPerformanceSummary.governance.peerGroupAvgHistory, function (index, score) {

                // create serial chart score
                var chartScore = ctx.createSerialChartMonthlyScore(scoreDic, score);

                // set value
                chartScore.avgScore = score.score == null ? "null" : ctx.$filter('number')(score.score, 2);
            });


            // get chart scores
            var chartScores = scoreDic.getValues();

            var chartOptions = ctx.createThemeSerialChartOptions('Governance');
            chartOptions.dataProvider = chartScores;

            return chartOptions;
        }

        private createSerialChartMonthlyScore(scoreDic: Common.Dictionary<SerialChartEsgMonthlyScore>, score: EsgCorporateMonthlyScoreDto): SerialChartEsgMonthlyScore {
            var ctx = this;

            // use month + year as key
            var month = ctx.$filter('date')(score.date, 'MMM yyyy');

            // get serial chart score by month
            var serialChartScore = scoreDic.getValue(month);

            // if the score does not exist in dictionary then create it
            if (!serialChartScore) {
                serialChartScore = new SerialChartEsgMonthlyScore();

                serialChartScore.month = month;
                scoreDic.add(month, serialChartScore);
            }

            return serialChartScore;
        }

        private createOverallSerialChartOptions(): Charts.SerialChartOptions {
            var options: any =
                {

                    "categoryField": "month",
                    "marginBottom": 0,
                    "marginLeft": 0,
                    "marginRight": 0,
                    "marginTop": 0,
                    "type": "serial",
                    "sequencedAnimation": false,
                    "pathToImages": "//cdn.amcharts.com/lib/3/images/",
                    "fontFamily": "Calibri",
                    "fontSize": 13,
                    "percentPrecision": 2,
                    "precision": 0,
                    "categoryAxis": {
                        "gridPosition": "start",
                        "minPeriod": "MM",
                        "parseDates": true,
                        "autoGridCount": false,
                        "gridCount": 3,
                        "tickLength": -1
                    },


                    "trendLines": [],
                    "graphs": [
                        {
                            "balloonText": "[[title]] of [[category]]:[[value]]",

                            "bullet": "diamond",
                            "fillColors": "#92E3CA",
                            "id": "AmGraph-1",
                            "lineColor": "#92E3CA",
                            "lineThickness": 2,
                            "periodSpan": 0,
                            "precision": 0,
                            "title": "Industry Leader",
                            "valueField": "leaderScore"
                        },
                        {
                            "balloonText": "[[title]] of [[category]]:[[value]]",
                            "bullet": "diamond",
                            "dashLength": 10,
                            "fillColors": "#fcaf17",
                            "fixedColumnWidth": 0,
                            "id": "AmGraph-2",
                            "lineColor": "#fcaf17",
                            "lineThickness": 2,
                            "minDistance": 0,
                            "negativeBase": 2,
                            "periodSpan": 0,
                            "title": "Company Score",
                            "valueField": "currentScore"
                        },
                        {
                            "balloonText": "[[title]] of [[category]]:[[value]]",
                            "id": "AmGraph-7",
                            "bullet": "diamond",
                            "fillColors": "#19746a",
                            "lineColor": "#19746a",
                            "lineThickness": 2,
                            "periodSpan": -1,
                            "title": "Industry Average",
                            "valueField": "avgScore"
                        }
                    ],
                    "guides": [],
                    "valueAxes": [
                        {
                            "id": "ValueAxis-1",
                            "maximum": 0,
                            "minimum": 100,
                            "minVerticalGap": 20,
                            "minMaxMultiplier": 0,
                            "title": "Score"
                        }
                    ],
                    "allLabels": [],
                    "balloon": {},
                    "legend": {
                        "align": "center",
                        "left": -3,
                        "marginBottom": -3,
                        "position": "top",
                        "useGraphSettings": true
                    },
                    "titles": [
                        {
                            "id": "Title-1",
                            "size": 15,
                            "text": ""
                        }
                    ]
                };

            return options;
        }

        private createThemeSerialChartOptions(title: string): Charts.SerialChartOptions {
            var options: any =
                {
                    "categoryField": "month",
                    "marginBottom": 0,
                    "marginLeft": 0,
                    "marginRight": 0,
                    "marginTop": 0,
                    "type": "serial",
                    "sequencedAnimation": false,
                    "pathToImages": "//cdn.amcharts.com/lib/3/images/",
                    "fontFamily": "Calibri",
                    "fontSize": 13,
                    "trendLines": [],
                    "categoryAxis": {
                        "gridPosition": "start",
                        "minPeriod": "MM",
                        "parseDates": true,
                        "autoGridCount": false,
                        "gridCount": 3,
                        "tickLength": -1
                    },
                    "graphs": [
                        {
                            "balloonText": "[[title]] of [[category]]:[[value]]",
                            "bullet": "diamond",
                            "bulletSize": 1,
                            "fillColors": "#92E3CA",
                            "id": "AmGraph-1",
                            "lineColor": "#92E3CA",
                            "lineThickness": 2,
                            "periodSpan": 0,
                            "precision": 0,
                            "title": "Industry Leader",
                            "valueField": "leaderScore",
                            "visibleInLegend": false
                        },
                        {
                            "balloonText": "[[title]] of [[category]]:[[value]]",
                            "bullet": "diamond",
                            "bulletSize": 1,
                            "dashLength": 10,
                            "fixedColumnWidth": 0,
                            "fillcolor": "#fcaf17",
                            "id": "AmGraph-2",
                            "lineColor": "#fcaf17",
                            "lineThickness": 2,
                            "minDistance": 0,
                            "negativeBase": 2,
                            "periodSpan": 0,
                            "title": "Company Score",
                            "valueField": "currentScore",
                            "visibleInLegend": false
                        },
                        {
                            "balloonText": "[[title]] of [[category]]:[[value]]",
                            "id": "AmGraph-7",
                            "bullet": "diamond",
                            "bulletSize": 1,
                            "fillcolor": "#19746a",
                            "lineColor": "#19746a",
                            "lineThickness": 2,
                            "periodSpan": -1,
                            "title": "Industry Average",
                            "valueField": "avgScore",
                            "visibleInLegend": false
                        }
                    ],
                    "guides": [],
                    "valueAxes": [
                        {
                            "id": "ValueAxis-1",
                            "maximum": 0,
                            "minimum": 100,
                            "minVerticalGap": 20,
                            "minMaxMultiplier": 0,
                            "title": "Score"
                        }
                    ],
                    "allLabels": [],
                    "balloon": {},
                    "legend": {
                        "align": "center",
                        "left": -3,
                        "marginBottom": -3,
                        "position": "top",
                        "useGraphSettings": true
                    },
                    "titles": [
                        {
                            "id": "Title-1",
                            "size": 18,
                            "text": title
                        }
                    ]
                };

            return options;
        }

        public getEsgPosition(): any {
            return EsgPositionEnum;
        }

        public getEsgPositionName(esgPosition: EsgPositionEnum): string {
            return EsgUtility.getEsgPositionName(esgPosition);
        }
    }


    export var historicalPerformanceControllerName = 'HistoricalPerformanceController';

    angular.module(esgRatingsModuleName).controller(historicalPerformanceControllerName, HistoricalPerformanceController);
}